package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.album.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountLockResultVo;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private OrderDerateMapper orderDerateMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Autowired
    private KafkaService kafkaService;



    @Override
    public OrderInfoVo trade(Long userId, TradeVo tradeVo) {

        BigDecimal originalAmount = new BigDecimal("0.00");
        //折扣金额
        BigDecimal derateAmount = new BigDecimal("0.00");
        //订单金额
        BigDecimal orderAmount = new BigDecimal("0.00");
        //订单明细列表
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //订单减免列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //查询用户的基本信息
        UserInfoVo userInfoVo = userFeignClient.getUserInfoVoByUserId(userId).getData();
        Assert.notNull(userInfoVo,"用户服务是失败,请联系管理员");
        //要付款的类型 itemType : 1003 是vip
        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(tradeVo.getItemType())){
            //vip  查询vip 的 详情
            VipServiceConfig vipConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();
            Assert.notNull(vipConfig, "VIP套餐不存在，请联系管理员");
            //原价
            originalAmount =   vipConfig.getPrice();
            //折扣
            orderAmount =   vipConfig.getDiscountPrice();
            //订单金额 = 原件 - 折扣
            derateAmount =  originalAmount.subtract(orderAmount);


            //封装订单明细
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(vipConfig.getName());
            orderDetailVo.setItemUrl(vipConfig.getImageUrl());
            orderDetailVo.setItemPrice(vipConfig.getPrice());

            orderDetailVoList.add(orderDetailVo);
            //订单折扣价格
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
            orderDerateVo.setDerateAmount(derateAmount);
            orderDerateVo.setRemarks("VIP折扣价：" + derateAmount);
            orderDerateVoList.add(orderDerateVo);


        } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())) {
            //专辑 处理 item_type为1001专辑吧?
            //判断用户是否购买过改专辑-> 远程调用 是否购买该专辑
            Boolean isPaid = userFeignClient.userInfoIsPaidAlbum(tradeVo.getItemId()).getData();
            if (isPaid){
                throw  new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
            }
            //要购买 ->远程调用该专辑的信息
            AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfoById(tradeVo.getItemId()).getData();
            Assert.notNull(albumInfo,"专辑信息不存在,请联系管理员上架该专辑");
            originalAmount = albumInfo.getPrice();
            //订单价格
            orderAmount = originalAmount;
            //判断是否是vip 还是普通用户 因为有对应的折扣信息
            if (userInfoVo.getIsVip().intValue() ==1 && userInfoVo.getVipExpireTime().after(DateUtil.date())){
                if (albumInfo.getVipDiscount().intValue() != -1){
                    //当前vip用户
                    orderAmount = originalAmount.multiply(albumInfo.getVipDiscount()).divide(new BigDecimal("10"),2,BigDecimal.ROUND_HALF_UP);
                    //优惠价格
                    derateAmount = originalAmount.subtract(orderAmount);
                }
            }
            else {
                if (albumInfo.getDiscount().intValue() != -1){
                    //普通用户购买专辑
                    orderAmount = originalAmount.multiply(albumInfo.getDiscount()).divide(new BigDecimal("10"),2,BigDecimal.ROUND_HALF_UP);
                    //优惠价格
                    derateAmount = originalAmount.subtract(orderAmount);
                }

            }
            //订单明细 集合
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(originalAmount);

            orderDetailVoList.add(orderDetailVo);
            //订单优惠信息
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
            orderDerateVo.setDerateAmount(derateAmount);

            orderDerateVo.setRemarks("优惠价格" + derateAmount);
            orderDerateVoList.add(orderDerateVo);


        }else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(tradeVo.getItemType())) {
            List<TrackInfo> waitPayTrackInfoList = albumInfoFeignClient.getWaitPayTrackInfoList(tradeVo.getItemId(), tradeVo.getTrackCount()).getData();

            //5.2 远程调用"专辑服务"获取专辑信息-得到声音单价
            AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfoById(waitPayTrackInfoList.get(0).getAlbumId()).getData();

            BigDecimal price = albumInfo.getPrice();

            //5.3 计算价格：原价，订单价 声音不支持折扣     返回几个 就乘以几个
            originalAmount = price.multiply(BigDecimal.valueOf(waitPayTrackInfoList.size()));
            orderAmount = originalAmount;

            //5.4 遍历待购声音列表构建订单明细集合
            orderDetailVoList = waitPayTrackInfoList.stream().map(trackInfo -> {
                OrderDetailVo orderDetailVo = new OrderDetailVo();
                orderDetailVo.setItemId(trackInfo.getId());
                orderDetailVo.setItemName(trackInfo.getTrackTitle());
                orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                orderDetailVo.setItemPrice(price);
                return orderDetailVo;
            }).collect(Collectors.toList());
        }

        OrderInfoVo orderInfoVo = new OrderInfoVo();

        //6.1 针对本次请求产生流水号，订单被重复条件（提交后回退到页面后继续提交） 将流水存入Redis，方便后续提交订单验证流水号
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        String tradeNo = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo);
        //支付类型
//        orderInfoVo.setPayWay();
        orderInfoVo.setItemType(tradeVo.getItemType());
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        //订单明细
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        //订单减免
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        //6.2 针对本次请求所有参数进行签名 --->md5（参数）=签名值 防止数据被网络传输过程中被恶意篡改
        orderInfoVo.setTimestamp(DateUtil.current());
        //将Bean对象转为Map 将对象中空值排除掉：支付类型"payway"
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);
        return orderInfoVo;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> submitOrder(Long userId, OrderInfoVo orderInfoVo) {
        //1.校验签名 是否正确
        Map<String, Object> paramMap = BeanUtil.beanToMap(orderInfoVo);
        paramMap.remove("payWay");
        //1.2 调用工具方法验证签名
        SignHelper.checkSign(paramMap);
        //2.检验订单号是否重复 使用lua 保证删除得原子性
        //2.1 先通过流水号Key查询Redis中正确流水号
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //2.2 跟用户提交流水号比对 比对成功后，将流水号删除（保证原子性-lua脚本）
        String script = "if(redis.call('get', KEYS[1]) == ARGV[1]) then return redis.call('del', KEYS[1]) else return 0 end";
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Boolean.class);
        //保证其原子性
        Boolean flag = (Boolean) redisTemplate.execute(redisScript, Arrays.asList(tradeKey), orderInfoVo.getTradeNo());
        if (!flag){
            throw new GuiguException(ResultCodeEnum.ORDER_SUBMIT_REPEAT);
        }
        //3.保存订单明细/dereate信息
        OrderInfo orderInfo = this.saveOrder(userId,orderInfoVo);

        if (SystemConstant.ORDER_PAY_ACCOUNT.equals(orderInfoVo.getPayWay())) {
            try {
                //4.1 远程调用“账户微服务”-检查及锁定可用余额
                AccountLockVo accountLockVo = new AccountLockVo();
                accountLockVo.setOrderNo(orderInfo.getOrderNo());
                accountLockVo.setUserId(userId);
                accountLockVo.setAmount(orderInfoVo.getOrderAmount());
                accountLockVo.setContent(orderInfoVo.getOrderDetailVoList().get(0).getItemName());
                Result<AccountLockResultVo> lockResult = accountFeignClient.checkAndLock(accountLockVo);
                if (200 != lockResult.getCode() || lockResult.getData() == null) {
                    log.error("[订单服务]远程调用账户服务进行锁定可用余额失败:业务状态码：{},信息：{}", lockResult.getCode(), lockResult.getMessage());
                    //锁定金额异常，订单也必须回滚
                    throw new GuiguException(lockResult.getCode(), lockResult.getMessage());
                }
                //4.1 发送消息,通知账户微服务扣减 账户余额 + 增加订单明细
                kafkaService.sendMessage(KafkaConstant.QUEUE_ACCOUNT_MINUS, orderInfo.getOrderNo());
                //修改支付状态:
                orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
                orderInfoMapper.updateById(orderInfo);
                //利用mq 处理订单购买记录
                UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
                userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
                userPaidRecordVo.setUserId(userId);
                userPaidRecordVo.setItemType(orderInfoVo.getItemType());
                //zhg OOPS
                List<Long> itemIdList = orderInfoVo.getOrderDetailVoList().stream().map(OrderDetailVo::getItemId).collect(Collectors.toList());
                userPaidRecordVo.setItemIdList(itemIdList);
                //监听 对应购买的记录 用户真正买的什么东西 vip /声音 /专辑 信息等等
                kafkaService.sendMessage(KafkaConstant.QUEUE_USER_PAY_RECORD, JSON.toJSONString(userPaidRecordVo));
                //4.判断余额type 1103
            }catch (Exception e){
                //以上情况出现异常 ,就进行回滚
                //将账户锁定的余额进行解锁:
                //.利用kafka消息完成解锁
                kafkaService.sendMessage(KafkaConstant.QUEUE_ACCOUNT_UNLOCK, orderInfo.getOrderNo());
            }
        }

        //5.封装订单编号

        Map<String, String> map = new HashMap<>();

        map.put("orderNo", orderInfo.getOrderNo());
        //6.发送延迟消息,用户未在30s支付 订单就会被关闭
        this.sendDelayMessage(orderInfo.getId());

        return map;
    }


    /**
     * 保存订单以及订单明细，订单优惠明细
     * 1.订单相关信息order-info封装为订单对象，向订单表中添加一条记录
     * 2.将提交订单明细信息order-detial封装为订单明细对象，批量向订单明细表中添加多条记录
     * 3.将订单优惠明细信息order-derate封装为订单优惠明细对象，批量向订单优惠明细表中添加多条记录
     * @param userId 用户id
     * @param orderInfoVo 订单信息
     * @return
     */
    @Override
    public OrderInfo saveOrder(Long userId, OrderInfoVo orderInfoVo) {
        //1.订单相关信息order-info封装为订单对象，向订单表中添加一条记录
        OrderInfo orderInfo =     BeanUtil.copyProperties(orderInfoVo,OrderInfo.class);
        //用户id
        orderInfo.setUserId(userId);
        //订单标题
        orderInfo.setOrderTitle(orderInfoVo.getOrderDetailVoList().get(0).getItemName());
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        //生成一个订单号 yyyyMMdd + 雪花算法
        String orderNo = DateUtil.today().replaceAll("-","") + IdUtil.getSnowflakeNextId();
        orderInfo.setOrderNo(orderNo);

        orderInfoMapper.insert(orderInfo);

        Long orderId = orderInfo.getId();

        //保存订单明细表
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        if (CollectionUtil.isNotEmpty(orderDetailVoList)){
            orderDetailVoList.stream().forEach(orderDetailVo -> {
                OrderDetail orderDetail =   BeanUtil.copyProperties(orderDetailVo, OrderDetail.class);
                orderDetail.setOrderId(orderId);
                orderDetailMapper.insert(orderDetail);
            });
        }

        //3.将提交优惠明细封装为优惠明细集合，批量向优惠明细表新增若干条记录
        List<OrderDerateVo> orderDerateVoList = orderInfoVo.getOrderDerateVoList();
        if (CollectionUtil.isNotEmpty(orderDerateVoList)) {
            orderDerateVoList.stream().forEach(orderDerateVo -> {
                OrderDerate orderDerate = BeanUtil.copyProperties(orderDerateVo, OrderDerate.class);
                orderDerate.setOrderId(orderId);
                orderDerateMapper.insert(orderDerate);
            });
        }


        return orderInfo;
    }

    @Override
    public Page<OrderInfo> getUserOrderByPage(Page<OrderInfo> pageInfo, Long userId) {
        pageInfo = orderInfoMapper.getUserOrderByPage(pageInfo, userId);
        //设置订单状态跟支付方式：中文
        pageInfo.getRecords().forEach(orderInfo -> {
            orderInfo.setOrderStatusName(this.getOrderStatusName(orderInfo.getOrderStatus()));
            orderInfo.setPayWayName(this.getPayWayName(orderInfo.getPayWay()));
        });
        return pageInfo;
    }

    @Override
    public OrderInfo getOrderInfo(Long userId, String orderNo) {
        //1.根据订单编号+用户ID查询订单信息
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        queryWrapper.eq(OrderInfo::getUserId, userId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (orderInfo != null) {
            //2.根据订单ID查询订单明细
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
            orderInfo.setOrderDetailList(orderDetailList);
            orderInfo.setPayWayName(this.getPayWayName(orderInfo.getPayWay()));
            orderInfo.setOrderStatusName(this.getOrderStatusName(orderInfo.getOrderStatus()));
            //3.根据订单ID查询订单优惠明细
            LambdaQueryWrapper<OrderDerate> orderDerateLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDerateLambdaQueryWrapper.eq(OrderDerate::getOrderId, orderInfo.getId());
            List<OrderDerate> orderDerateList = orderDerateMapper.selectList(orderDerateLambdaQueryWrapper);
            orderInfo.setOrderDerateList(orderDerateList);
            return orderInfo;
        }
        return null;

    }

    /**
     * 使用Redisson 的延迟队列 进行关闭订单
     */
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void sendDelayMessage(Long orderId) {
        try {
            //基于RedissonClient创建阻塞队列
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
            //将阻塞队列作为参数创建延迟队列
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);

            //调用延迟队列方法进行发送消息
            delayedQueue.offer(orderId.toString(),30 ,TimeUnit.SECONDS);
            log.info("添加延迟队列成功,延迟时间:{},订单id:{}",30,orderId);
        } catch (Exception e) {
            log.error("添加延迟队列失败");
            throw new RuntimeException(e);
        }
    }

    @Override
    public void orderCancel(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
            orderInfoMapper.updateById(orderInfo);
        }
    }


    /**
     * 根据支付方式编号得到支付名称
     *
     * @param payWay
     * @return
     */
    private String getOrderStatusName(String orderStatus) {
        if (SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)) {
            return "未支付";
        } else if (SystemConstant.ORDER_STATUS_PAID.equals(orderStatus)) {
            return "已支付";
        } else if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderStatus)) {
            return "取消";
        }
        return null;
    }


    /**
     * 根据支付方式编号得到支付名称
     *
     * @param payWay
     * @return
     */
    private String getPayWayName(String payWay) {
        if (SystemConstant.ORDER_PAY_WAY_WEIXIN.equals(payWay)) {
            return "微信";
        } else if (SystemConstant.ORDER_PAY_ACCOUNT.equals(payWay)) {
            return "余额";
        } else if (SystemConstant.ORDER_PAY_WAY_ALIPAY.equals(payWay)) {
            return "支付宝";
        }
        return "";
    }

}
